//
//  UIButton+CountDown.m
//
//  Created by LiXiaoFeng on 14/12/29.
//  Copyright © 2014年 LiXiaoFeng. All rights reserved.
//

#import "UIButton+CountDown.h"
#import <objc/runtime.h>

const char endCountDownKey;

@implementation UIButton (CountDown)

-(BOOL)xx_endCountDown{
    return [objc_getAssociatedObject(self, (void *)&endCountDownKey) boolValue];
}
-(void)setXx_endCountDown:(BOOL)xx_endCountDown{
    self.enabled = endCountDownKey;
    objc_setAssociatedObject(self, (void *)&endCountDownKey, [NSNumber numberWithBool:endCountDownKey], OBJC_ASSOCIATION_COPY);
}

-(void)xx_startCountDown:(NSInteger)count showText:(NSString *)text complete:(void (^)(UIButton *buttom))complete;{
    [self setXx_endCountDown:NO];
    __weak typeof(self) weakSelf = self;
    
    [self setTitle:[NSString stringWithFormat:text,count] forState:UIControlStateNormal];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.xx_endCountDown || count <= 0) {
                [self setXx_endCountDown:YES];
                complete(self);
                return;
            }
            [weakSelf xx_startCountDown: count - 1 showText:text complete:complete];
        });
    });
}

@end
